var express = require('express');
var router = express.Router();
var { User } = require('../module/liujiangxin');
const smsClient = require('@alicloud/sms-sdk');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

const SECRET_KEY = 'your-secret-key'; // 在实际应用中应该使用环境变量

// 测试路由
router.get('/test', async (req, res) => {
  try {
    // 测试数据库连接
    const count = await User.countDocuments();
    res.json({ 
      message: 'Test route working', 
      dbStatus: 'Connected',
      userCount: count 
    });
  } catch (error) {
    console.error('Test route error:', error);
    res.status(500).json({ 
      message: 'Test failed', 
      error: error.message 
    });
  }
});

// 注册接口
router.post('/register', async (req, res) => {
  try {
    console.log('Received register request:', req.body); // 添加日志
    const { username, password, phone } = req.body;

    if (!username || !password || !phone) {
      return res.status(400).json({ message: '请填写完整信息' });
    }

    const existingUser = await User.findOne({ 
      $or: [{ username }, { phone }] 
    });
    
    if (existingUser) {
      return res.status(400).json({ 
        message: existingUser.username === username ? 
          '该账号已被注册' : '该手机号已被注册' 
      });
    }

    const hashedPassword = await bcrypt.hash(password, 10);
    const user = new User({
      username,
      password: hashedPassword,
      phone
    });

    await user.save();
    console.log('User registered successfully:', username);
    res.status(201).json({ message: '注册成功' });
  } catch (error) {
    console.error('Register error:', error);
    res.status(500).json({ message: '注册失败，请稍后重试' });
  }
});

// 账号密码登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    // 查找用户
    const user = await User.findOne({ username });
    if (!user) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, user.password);
    if (!isValidPassword) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    // 生成 token
    const token = jwt.sign(
      { userId: user._id, username: user.username },
      SECRET_KEY,
      { expiresIn: '24h' }
    );

    res.json({
      token,
      user: {
        username: user.username,
        phone: user.phone
      }
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ message: '登录失败，请稍后重试' });
  }
});

// 手机号登录
router.post('/login/phone', async (req, res) => {
  try {
    const { phone, verificationCode } = req.body;
    
    // 验证验证码（这里需要实现验证码验证逻辑）
    // TODO: 验证验证码

    // 查找用户
    const user = await User.findOne({ phone });
    if (!user) {
      return res.status(401).json({ message: '手机号未注册' });
    }

    // 生成 token
    const token = jwt.sign(
      { userId: user._id, username: user.username },
      SECRET_KEY,
      { expiresIn: '24h' }
    );

    res.json({
      token,
      user: {
        username: user.username,
        phone: user.phone
      }
    });
  } catch (error) {
    console.error('手机号登录错误:', error);
    res.status(500).json({ message: '登录失败，请稍后重试' });
  }
});

// 发送验证码
router.post('/send-code', async (req, res) => {
  try {
    const { phone } = req.body;
    
    // TODO: 实现发送验证码的逻辑
    // 这里需要集成短信服务商的 SDK

    res.json({ message: '验证码已发送' });
  } catch (error) {
    console.error('发送验证码错误:', error);
    res.status(500).json({ message: '发送验证码失败，请稍后重试' });
  }
});

module.exports = router;
